﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.db.Models.Systems;
using com.nm.Helper;
using george.Helper;

// ReSharper disable once CheckNamespace
namespace com.nm.ApiServer {
	/// <summary>
	/// Api访问日志
	/// </summary>
	public class ApiLog {
		/// <summary>
		/// 唯一ID
		/// 使用创建对象时的 DateTime.Now.Ticks
		/// </summary>
		public long ID { get; set; }
		/// <summary>
		/// IP 地址
		/// </summary>
		public string IpAddress { get; set; }
		/// <summary>
		/// 开始时间
		/// </summary>
		public DateTime BeginTime { get; set; }
		/// <summary>
		/// 结束时间
		/// </summary>
		public DateTime EndTime { get; set; }
		/// <summary>
		/// 控制器
		/// </summary>
		public string Controller { get; set; }
		/// <summary>
		/// 动作
		/// </summary>
		public string Action { get; set; }
		/// <summary>
		/// 输入的参数
		/// </summary>
		public string Params { get; set; }
		/// <summary>
		/// 用户ID（如果有）
		/// </summary>
		public int CusID { get; set; }
		/// <summary>
		/// 执行是否成功
		/// </summary>
		public bool IsSuccess { get; set; }
		/// <summary>
		/// 错误代码
		/// </summary>
		public int ErrorCode { get; set; }
		/// <summary>
		/// 信息（一般是错误信息）
		/// </summary>
		public string Message { get; set; }
		/// <summary>
		/// 调用API的app名称
		/// </summary>
		public string AppName { get; set; }
		/// <summary>
		/// 调用API的app的ID
		/// </summary>
		public Guid AppID { get; set; }

	    const int ExpiryMonthInMinutes = 60*24*7;
        /// <summary>
        /// 保存日志到Redis
        /// </summary>
        /// <param name="log"></param>
        public static async Task SaveAsync(ApiLog log) {
            //DO NOT THING

            using (var redis = new RedisClient(ConfigurationHelper.Get("redis-apilog-index", 3)))
            {
                var db = redis.GetDatabase();
                //插入检索
                var type = "apilog:";
                log.ID = db.StringIncrement(type + "count");
                //log.ID = DateTime.Now.Ticks;
                redis.SetString(type + log.ID + ":CusID", log.CusID, ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":IpAddress", log.IpAddress, ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":Action", log.Action, ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":Controller", log.Controller, ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":ErrorCode", log.ErrorCode, ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":Message", log.Message, ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":IsSuccess", log.IsSuccess, ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":Params", log.Params.Left(200), ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":BeginTime", log.BeginTime, ExpiryMonthInMinutes);
                redis.SetString(type + log.ID + ":EndTime", log.EndTime, ExpiryMonthInMinutes);
                if (log.AppID != Guid.Empty)
                {
                    redis.SetString(type + log.ID + ":AppName", log.AppName, (ExpiryMonthInMinutes));
                    redis.SetString(type + log.ID + ":AppID", log.AppID.ToString(), (ExpiryMonthInMinutes));
                }
                //插入检索
                db.SetAdd(string.Format("{2}{0}:{1}", log.Controller, log.Action, type), log.ID);
                if (log.AppID != Guid.Empty)
                {
                    db.SetAdd(type + "AppID", log.AppID.ToString());
                    db.SetAdd(type + "AppName", log.AppName);
                }
                if (!log.IsSuccess)
                {
                    db.SetAdd(type + "error", log.ID);
                }
            }
        }

        /// <summary>
        /// 记录系统日志
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
	    public static async Task SavaSysLog(sys_log log)
	    {
	        var dc = new SysEntities();
	        var data = new sys_log
	        {
	            Action = log.Action,
	            CreateTime = log.CreateTime,
	            HostAddress = log.HostAddress,
	            LogContent = log.LogContent,
	            OperationType = log.OperationType,
	            Operator = log.Operator
	        };
	        dc.sys_log.Add(data);
	        try
	        {
	            dc.SaveChanges();
	        }
	        catch (Exception ex)
	        {
	            Log.Error("记录系统访问日志:"+ ex+data);
	        }
	    }
	}
}
